<template>
  <div class="menu-wrapper">
    <el-form ref="receiverForm" :model="form" :rules="rules" label-width="100px">
      <div v-if="!memberId" style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">基本信息</span>
      </div>
      <div style="display: flex;">
          <el-form-item label="客户名称" prop="memberId">
            <el-select v-model="form.memberId" style="width: 220px" disabled>
              <el-option v-for="item in memberIdOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
      </div>
      <div style="display: flex;">
          <el-form-item label="收货人姓名" prop="consignee">
            <el-input v-model="form.consignee" style="width: 220px" />
          </el-form-item>
      </div>
      <div style="display: flex;">
          <el-form-item label="收货人电话" prop="phone">
            <el-input v-model="form.phone" type="number" style="width: 220px" />
          </el-form-item>
      </div>
      <div style="display: flex">
        <el-form-item label="所在地" prop="areaName" :rules="rules.areaName">
          <div style="display: flex; justify-content: space-between">
            <Distpicker :province="district.province" :city="district.city" :area="district.area" @selected="onSelected" style="width:450px" />
            <el-button  type="primary" style="margin-left:10px; height:36px; padding: 0 20px;"  @click="mapShowFn"><i class="el-icon-map-location" /></el-button>
          </div>
        </el-form-item>
      </div>
      <div style="display: flex">
        <div style="display: flex;">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.building" style="width: 520px" placeholder="道路、小区/楼/村，例：厦门市思明区龙山中路84号启达大厦" />
          </el-form-item>
        </div>
      </div>

      <div style="display: flex;">
        <el-form-item label="门牌号" prop="roomNumber">
          <el-input v-model="form.roomNumber" style="width: 380px" placeholder="请输入门牌号，例：220室" />
        </el-form-item>
        <el-form-item label="楼层" prop="level" label-width="50px">
          <el-select v-model="form.level" style="width: 90px" placeholder="请选择">
            <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </div>

      <div style="display: flex;">
          <el-form-item label="设为默认地址" prop="isDefault">
            <el-switch
              v-model="form.isDefault"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
      </div>

      <el-form-item>
        <el-button v-permission="['member.query']" type="primary" :loading="clicked" @click="saveReceiver('receiverForm')">
          完 成
        </el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="位置信息"
      :visible.sync="mapShow"
      top="5vh"
      width="800px"
      :before-close="handleClose"
    >
      <Map :setcenter="[form.lng, form.lat]" @getMap="getMap" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="mapShow = false">取 消</el-button>
        <el-button type="primary" @click="savelngLat">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { EventBus } from '@/api/eventBus'
import utils from '../../utils/utils.js'
import Distpicker from '@/components/Distpicker/Distpicker'
import Map from '@/components/GaodeMap/index'
import { find, update } from '@/api/receiver'
import permission from '@/directive/permission/index.js' // 权限判断指令
import { list as memberList, find as memberFind } from '@/api/member'
export default {
  name: 'Edit',
  directives: { permission },
  components: { Map, Distpicker },
  props: ['memberId', 'pathType', 'id'],
  data() {
    return {
         levelOptions: [
        { label: '有电梯', value: 0 },
        { label: '一层楼', value: 1 },
        { label: '二层楼', value: 2 },
        { label: '三层楼', value: 3 },
        { label: '四层楼', value: 4 },
        { label: '五层楼', value: 5 },
        { label: '六层楼', value: 6 },
        { label: '七层楼', value: 7 },
        { label: '八层楼', value: 8 },
        { label: '九层及以上', value: 9 }
      ],
      clicked: false, // 按钮防双击
      mapShow: false,
      tempLng: '',
      tempLat: '',
      tempAddress: '',
      tempAreaId: '',
      tempAois: '',
      tempAreaName: '',
      memberIdOptions: [],
      district:{},
      form: {
        id: '',
        address: '', // 详细地址
        areaName: '',
        areaId: '', // 地区
        building: '', // 小区/大楼
        consignee: '',
        isDefault: true, // 是否默认
        lat: '', // 纬度
        level: '', // 楼层
        lng: '', // 经度
        mapLineId: '', // 地区
        memberId: '', // 会员
        phone: '', // 电话
        roomNumber: '' // 门牌号
      },
      rules: {
        memberId: [
          { required: true, message: '请选择用户名', trigger: 'blur' }
        ],
        consignee: [
          { required: true, message: '请输入收货人', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        building: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        areaName: [
          { required: true, message: '请输入所在地', trigger: 'blur' }
        ],
        roomNumber: [
          { required: true, message: '请输入门牌号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.findReceiver()
    this.queryMember()
    this.initMemberData()
  },
  methods: {

   findReceiver() {
      if (!utils.isNull(this.id) || !utils.isNull(this.$route.query.id)) { // 有就用prop传入的id
        this.form.id = Number(this.id) || Number(this.$route.query.id)
      } else { // 否则就接收路由传递的id
        this.form.id = this.$route.query.id
      }

      find(this.form.id).then(res => {
        console.log(res)
        this.form = res.data

        const reg = /.+?(省|市|自治区|自治州|县|区)/g
        // console.log(this.form.address.match(reg)[0])
        this.district.province = this.form.areaName.match(reg)[0]
        this.district.city = this.form.areaName.match(reg)[1]
        this.district.area = this.form.areaName.match(reg)[2]

      }).catch(err => { console.log(err) })
    },
    initMemberData() {
      if (!utils.isNull(this.memberId) || !utils.isNull(this.$route.query.memberId)) { // 有就用prop传入的memberId
        this.form.memberId = Number(this.memberId) || Number(this.$route.query.memberId)
      } else { // 否则就接收路由传递的memberId
        this.form.memberId = this.$route.query.memberId
      }
      memberFind(this.form.memberId).then(res => {
        this.memberIdOptions.push(res.data.member)
      }).catch(err => {
        console.log(err)
      })
    },
    queryMember(query) { // 搜索客户
      // console.log(query)
      clearTimeout(this.memberMark)
      this.memberMark = setTimeout(() => {
        this.memberIdOptions = []
        memberList({ keyword: query }).then(res => {
          this.memberIdOptions = res.data.data
        }).catch(err => {
          console.log(err)
        })
      }, 300)
    },
    mapShowFn() {
      this.mapShow = !this.mapShow
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    getMap(lng, lat, addressData) {
      // console.log(lng, lat, addressData)
      // 定义变量保存经纬度和地址
      this.tempLng = lng
      this.tempLat = lat
      // this.tempAddress = addressData.formattedAddress
      this.tempAreaId = addressData.addressComponent.adcode
      // addressData.aois.length !== 0 ? this.tempAois = addressData.aois[0].name : this.tempAois
      this.tempAois = addressData.formattedAddress
      this.tempAreaName = `${addressData.addressComponent.province}${addressData.addressComponent.city}${addressData.addressComponent.district}`
    },
    savelngLat() {
      this.form.lng = this.tempLng
      this.form.lat = this.tempLat
      // this.form.address = this.tempAddress
      this.form.areaId = this.tempAreaId
      this.form.building = this.tempAois
      this.form.areaName = this.tempAreaName
      this.form.address = this.form.building
      this.mapShow = false
    },
    onSelected(val) {

      if (!utils.isNull(val.area) && !utils.isNull(val.area.code)) {
        this.form.areaId = val.area.code
        this.form.areaName = val.province.value+val.city.value+val.area.value
      }else if (!utils.isNull(val.city) && !utils.isNull(val.city.code)){
        this.form.areaId = val.city.code
        this.form.areaName = val.province.value+val.city.value

      }else if (!utils.isNull(val.province) && !utils.isNull(val.province.code)){
        this.form.areaId = val.province.code
        this.form.areaName = val.province.value
      }

    },
    saveReceiver(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          this.clicked = true
          const address = this.form.building + this.form.roomNumber
          const params = {
            id: this.form.id,
            address,
            areaName: this.form.areaName,
            consignee: this.form.consignee,
            isDefault: this.form.isDefault,
            lat: this.form.lat,
            lng: this.form.lng,
            memberId: this.form.memberId,
            phone: this.form.phone,
            roomNumber: this.form.roomNumber,
            building: this.form.building,
            createDate: new Date(),
                level:this.form.level
          }
          update(params).then(res => {
            console.log(res)
            if (res.type == 'success') {
              if (this.pathType == undefined) {
                EventBus.$emit('receiver-edit', res.data)
                this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
                  this.$router.push({
                    path: '/receiver/list'
                  })
                })// 关闭当前tab回到列表
              } else {
                this.$emit('orderReceiver', res)
              }
            } else { this.$message({ message: res.content, offset: 120, center: true }) }
            this.clicked = true
          }).catch(err => {
            this.clicked = false
            console.log(err)
          })
        }
      })
    }
  }
}
</script>

<style scoped>
  .menu-wrapper {
    margin: 15px;
  }
</style>
